Kernel.extend(Kernel, {
		
	doREST: function(config) {
		config.dataType = 'json';
		this.doAjax(config);
	},
	
	doAjax: function(config) {
		$.ajax({
			url: 'ajax.php/'+config.url,
			type: config.type,
			data: config.params,
			dataType: config.dataType,
			success: config.success,
			error: function(jqXHR, textStatus, errorThrown) {
				if (config.failure) {
					config.failure('Ajax call failed.');
				}
			}
		});
	},
	
	render: function(instance) {
		if (instance.widget) {
			this.renderWidget(instance)
		}
		else {
			this.renderModule(instance)
		}
	},
	
	renderWidget: function(instance) {
		if (typeof instance.file !== 'undefined') {
			if (instance.file !== "") {
				$.get('widgets/'+instance.title+'/'+instance.file+"?firstrun=1", function(data) {
					$("#"+instance.renderTo).html(data);
					instance.$moduleEl = $(instance.renderTo);
					instance.init();
				});
			} else {
				instance.$moduleEl = $(instance.renderTo);
				instance.init();
			}
		}
	},
	
	renderModule: function(instance) {
		var isRunning = $('#fsa-'+instance.title).length;
		var box = Kernel.sandbox.get('main');
		var innerHeight = window.innerHeight - 55;
		
		if (box.getmRunningTitle() !== instance.title) {
			if (isRunning == 0) {
				$.get('modules/'+instance.title+'/'+instance.file+"?firstrun=1", function(data) {
					$('body').append("<div id='fsa-"+instance.title+"' style='display:none; position: absolute; width: 100%; height: "+innerHeight+"px; color: #000; z-index: 90;-webkit-transform: translate3d(0, 0, 0);'>"+data+"</div>");
	
					if (box.getmRunningFSA()) {
						$( box.getmRunningFSA()).hide('slide');
					} else {
						//$( "#mainPage" ).hide('slide');
					}
					$( "#fsa-"+instance.title ).toggle('fade', 500);
	
					// Save reference to module element for later
					instance.$moduleEl = $(instance.renderTo);
	
					box.putmRunningTitle(instance.title);
					box.putmRunningFSA("#fsa-"+instance.title);
					box.mRunningList.push(instance.title);
			
					// Make sure to finally call init()
					instance.init();
				});		
			} else {
				$( "#fsa-"+instance.title ).toggle('fade', 500);	
				box.putmRunningTitle(instance.title);
				box.putmRunningFSA("#fsa-"+instance.title);
			}
		}

	},

	// startup gives you control over when module.init() gets called
	onStart: function(instance) {
		if (instance.file) {
			this.render(instance);
		}
		else {
			instance.init();
		}
	},
	
	onStop: function(instance) {
		
		// Allow module to handle its own shutdown first
		instance.kill();
		
		// Take care of any rendered elements
		var el = instance.$moduleEl;
	
		if (el) {
			el.fadeOut(500, function()
			{
				el.remove();
			});
		}
	}
});
